from datetime import time
import logging
from django.conf import settings
from wechatpayv3 import WeChatPay, WeChatPayType
#from wechatpayv3.core  import WeChatPayException
from .wechat_pay_service import WechatPayService

logger = logging.getLogger(__name__)

class WechatRefundService:
    def __init__(self, wechat_config=None):
        self.config = wechat_config or self._get_default_config()
        self.pay_service = WechatPayService(self.config)
        self.client = WeChatPay(
            appid=self.config['app_id'],
            mchid=self.config['mch_id'],
            private_key=self.config['private_key'],
            cert_serial_no=self.config['cert_serial_no'],
            wechatpay_cert=self.config['wechatpay_cert']
        )

    def _get_default_config(self):
        """获取默认微信支付配置"""
        return {
            'app_id': settings.WECHAT_APP_ID,
            'mch_id': settings.WECHAT_MCH_ID,
            'private_key': settings.WECHAT_PRIVATE_KEY,
            'cert_serial_no': settings.WECHAT_CERT_SERIAL_NO,
            'wechatpay_cert': settings.WECHAT_PAY_CERT,
        }

    def create_refund(self, order, refund_amount=None, reason="订单取消退款"):
        """
        创建微信退款
        :param order: Order实例
        :param refund_amount: 退款金额，默认为订单总金额
        :param reason: 退款原因
        :return: 退款结果
        """
        if order.payment_method != 'wechat':
            raise ValueError("仅微信支付订单支持自动退款")

        if order.status not in ['paid', 'confirmed', 'serving']:
            raise ValueError(f"订单状态为{order.status}，不支持退款")

        # 退款金额默认为订单总金额（单位：分）
        refund_amount = refund_amount or int(order.total_amount * 100)
        total_amount = int(order.total_amount * 100)

        try:
            # 调用微信支付退款接口
            out_refund_no = f"REFUND{order.order_number}{int(time.time())}"
            result = self.client.refund.create(
                out_trade_no=order.out_trade_no,  # 原支付订单号
                out_refund_no=out_refund_no,      # 退款单号
                reason=reason,
                amount={
                    "refund": refund_amount,
                    "total": total_amount,
                    "currency": "CNY"
                }
            )

            # 记录退款信息到订单
            order.refund_status = 'PROCESSING'
            order.out_refund_no = out_refund_no
            order.save()

            logger.info(f"订单[{order.id}]退款申请提交成功: {result}")
            return result

        # except WeChatPayException as e:
        #     logger.error(f"微信退款接口调用失败: {e}", exc_info=True)
        #     raise
        except Exception as e:
            logger.error(f"退款处理失败: {e}", exc_info=True)
            raise

    def query_refund(self, out_refund_no):
        """查询退款状态"""
        try:
            return self.client.refund.query_by_out_refund_no(out_refund_no)
        except Exception as e:
            logger.error(f"查询退款状态失败: {e}", exc_info=True)
            raise